import React,{useMemo} from 'react'
import { useNavigate,Navigate,useLocation } from 'react-router-dom';
import {useUser} from '@/hooks'

export function withNavigate(InnerComponent){
    return function WrapperComponent(props){
        console.log('WrapperComponent',props);// {a:10,b:true,c:1}
        const navigate = useNavigate()
        return <InnerComponent {...props} navigate={navigate} />
    }

}

/**
 * 根据用户是否登录实现页面访问权限控制
 * 已登录：可以访问页面
 * 未登录：回退到登录页面
 * @param {Component} InnerComponent 
 * @returns 
 */
export function withLogin(InnerComponent){
    return function WrapperComponent(props){
        const {userInfo} = useUser();
        const isLogin = useMemo(() => !!userInfo.authorization, [userInfo])

        // 用户访问目标页面
        const {pathname:targetUrl} = useLocation()

        return isLogin ? 
        <InnerComponent {...props} />
        :
        <Navigate to={"/login?target="+targetUrl} />
    }
}